package com.example.confirmcodedemo.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/admin")
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";

    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        //从session中获取验证码和日期
        String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);

        System.out.println("captcha: " + captcha);
        System.out.println("savecaptcha: " + saveCaptcha);

        if(captcha.equals(saveCaptcha)){
            if(saveDate != null && (System.currentTimeMillis() - saveDate.getTime()) < 60 * 1000){
                return true;
            }
        }
        return false;
    }
}
